package com.shsnc.agent;

import java.lang.reflect.Method;
import java.util.concurrent.Callable;

import cn.hutool.json.JSONUtil;
import com.shsnc.agent.bean.BaseLogInfoModel;
import com.shsnc.agent.bean.LogDetailModel;
import com.shsnc.agent.service.LogHandle;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.implementation.bind.annotation.AllArguments;
import net.bytebuddy.implementation.bind.annotation.Origin;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.implementation.bind.annotation.SuperCall;

/**
 *
 * @author zll
 * @date 2021/8/5
 */
@Slf4j
public class LogIntercept {

	@RuntimeType
	public static Object intercept(@Origin Method method,
			@AllArguments Object[] args,
			@SuperCall Callable<?> callable) throws Exception{
		long start = System.currentTimeMillis();
		Object resObj = null;
		try{
			resObj = callable.call();
			return resObj;
		}finally {
			try {
				log.info("方法名称：" + method.getName());
				log.info("入参个数：" + method.getParameterCount());
				log.info("入参类型：" + method.getParameterTypes()[0].getTypeName() + "、" + method.getParameterTypes()[1]
						.getTypeName());
				log.info("入参内容：" + JSONUtil.toJsonStr(args[0]) + "、" + JSONUtil.toJsonStr(args[1]));
				log.info("方法耗时：" + (System.currentTimeMillis() - start) + "ms");
				BaseLogInfoModel baseLog=JSONUtil.toBean(JSONUtil.toJsonStr(args[0]),BaseLogInfoModel.class);
				LogDetailModel logDetail=JSONUtil.toBean(JSONUtil.toJsonStr(args[1]),LogDetailModel.class);
				LogHandle logHandle=new LogHandle();
				logHandle.deal(baseLog,logDetail);
			}catch (Exception e){
				log.error("添加日志拦截出错：{}",e.getMessage());
			}
		}
	}
}
